<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="配置名称" prop="configName">
        <el-input v-model="queryParams.configName" placeholder="请输入配置名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="任务状态" clearable style="width: 240px">
          <el-option label="运行中" value="RUNNING" />
          <el-option label="已完成" value="SUCCESS" />
          <el-option label="失败" value="FAILED" />
          <el-option label="已取消" value="CANCELLED" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:crawler:task:add']">新建任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:crawler:task:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务名称" align="center" prop="taskName" :show-overflow-tooltip="true" />
      <el-table-column label="配置名称" align="center" prop="configName" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="爬取数量" align="center" prop="crawledCount" width="100" />
      <el-table-column label="保存数量" align="center" prop="savedCount" width="100" />
      <el-table-column label="失败数量" align="center" prop="failedCount" width="100" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行时长" align="center" prop="duration" width="120">
        <template #default="scope">
          <span v-if="scope.row.duration">{{ formatDuration(scope.row.duration) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"
            v-hasPermi="['system:crawler:task:query']">详情</el-button>
          <el-button v-if="scope.row.status === 'RUNNING'" link type="warning" icon="VideoPause" @click="handleStop(scope.row)"
            v-hasPermi="['system:crawler:task:stop']">停止</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:crawler:task:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="Number(total)" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新建任务对话框 -->
    <el-dialog title="新建爬虫任务" v-model="open" width="600px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="120px">
        
        <el-form-item label="选择配置" prop="configId">
          <el-select v-model="form.configId" placeholder="请选择爬虫配置" style="width: 100%">
            <el-option
              v-for="config in configList"
              :key="config.id"
              :label="config.configName"
              :value="config.id">
              <span style="float: left">{{ config.configName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ config.siteName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大页数" prop="maxPages">
              <el-input-number v-model="form.maxPages" :min="1" :max="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求间隔(毫秒)" prop="requestInterval">
              <el-input-number v-model="form.requestInterval" :min="1000" :max="10000" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">开始执行</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog title="任务详情" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务名称">{{ detailForm.taskName }}</el-descriptions-item>
        <el-descriptions-item label="配置名称">{{ detailForm.configName }}</el-descriptions-item>
        <el-descriptions-item label="任务状态">
          <el-tag :type="getStatusType(detailForm.status)">
            {{ getStatusText(detailForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="爬取数量">{{ detailForm.crawledCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="保存数量">{{ detailForm.savedCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="失败数量">{{ detailForm.failedCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(detailForm.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ parseTime(detailForm.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="执行时长" :span="2">
          {{ formatDuration(detailForm.duration) }}
        </el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2" v-if="detailForm.errorMessage">
          <el-tag type="danger">{{ detailForm.errorMessage }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="CrawlerTask">
import { listTask, getTask, executeTask, stopTask, delTask, delTaskBatch } from "@/api/system/crawler/task";
import { listConfig } from "@/api/system/crawler/config";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const taskList = ref([]);
const open = ref(false);
const detailOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const configList = ref([]);

const data = reactive({
  form: {},
  detailForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: undefined,
    configName: undefined,
    status: undefined
  },
  rules: {
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    configId: [
      { required: true, message: "请选择爬虫配置", trigger: "change" }
    ]
  }
});

const { queryParams, form, detailForm, rules } = toRefs(data);

/** 查询爬虫任务列表 */
function getList() {
  loading.value = true;
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows || [];
    total.value = Number(response.total) || 0;
    loading.value = false;
  });
}

/** 获取配置列表 */
function getConfigList() {
  listConfig({
    pageNum: 1,
    pageSize: 1000  // 设置较大的页面大小以获取所有配置
  }).then(response => {
    configList.value = response.rows;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getConfigList();
  open.value = true;
  title.value = "新建爬虫任务";
}

/** 详情按钮操作 */
function handleDetail(row) {
  const taskId = row.id || ids.value[0];
  getTask(taskId).then(response => {
    detailForm.value = response.data;
    detailOpen.value = true;
  });
}

/** 停止按钮操作 */
function handleStop(row) {
  const taskId = row.id || ids.value[0];
  proxy.$modal.confirm('是否确认停止任务"' + row.taskName + '"？').then(function() {
    return stopTask(taskId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("任务已停止");
  }).catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      const params = {
        configId: form.value.configId,
        maxPages: form.value.maxPages,
        requestInterval: form.value.requestInterval
      };
      executeTask(params).then(response => {
        proxy.$modal.msgSuccess("任务已启动");
        open.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const taskIds = row.id || ids.value;
  const taskNames = row ? row.taskName : '选中的任务';
  
  proxy.$modal.confirm('是否确认删除爬虫任务"' + taskNames + '"？').then(function() {
    if (Array.isArray(taskIds)) {
      // 批量删除
      return delTaskBatch(taskIds);
    } else {
      // 单个删除
      return delTask(taskIds);
    }
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    taskName: null,
    configId: null,
    maxPages: 1000,
    requestInterval: 2000,
    remark: null
  };
  proxy.resetForm("taskRef");
}

/** 获取状态类型 */
function getStatusType(status) {
  const statusMap = {
    'RUNNING': 'primary',
    'SUCCESS': 'success',
    'FAILED': 'danger',
    'CANCELLED': 'info'
  };
  return statusMap[status] || 'info';
}

/** 获取状态文本 */
function getStatusText(status) {
  const statusMap = {
    'RUNNING': '运行中',
    'SUCCESS': '已完成',
    'FAILED': '失败',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
}

/** 格式化执行时长 */
function formatDuration(duration) {
  if (!duration) return '-';
  const seconds = Math.floor(duration / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  
  if (hours > 0) {
    return `${hours}小时${minutes % 60}分钟${seconds % 60}秒`;
  } else if (minutes > 0) {
    return `${minutes}分钟${seconds % 60}秒`;
  } else {
    return `${seconds}秒`;
  }
}

getList();
</script> 